<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>获取 GitHub GHU</title>
    <style>
        body, html {
            height: 100%;
            margin: 0;
            display: flex;
            justify-content: center;
            align-items: center;
            font-family: Arial, sans-serif;
            background-color: #f0f0f0;
        }

        .login-container {
            background-color: white;
            padding: 6em;
            border-radius: 10px;
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
            text-align: center;
            box-sizing: border-box;
            width: 50vw; /* 添加固定宽度 */
            min-width: 450px; /* 添加最小宽度 */
            max-width: 650px;
        }

        input {
            width: 100%;
            padding: 1em;
            margin: 0.5em 0;
            border: 1px solid #ccc;
            border-radius: 5px;
            box-sizing: border-box; /* 确保填充和边框包含在宽度和高度中 */
            font-size: 16px;
        }

        .submit-button {
            width: 100%;
            padding: .8em;
            margin-top: 1em;
            border: none;
            border-radius: 5px;
            background-color: #007bff;
            color: white;
            font-size: 1em;
            cursor: pointer;
        }

        .submit-button:hover {
            background-color: #0056b3;
        }

        /* Dark mode styles */
        @media (prefers-color-scheme: dark) {
            body, html {
                background-color: #121212;
                color: white;
            }

            .login-container {
                background-color: #1e1e1e;
                box-shadow: 0 4px 8px rgba(0, 0, 0, 0.5);
            }

            input {
                background-color: #2e2e2e;
                border: 1px solid #444;
                color: white;
            }

            input::placeholder {
                color: #888;
            }

            .submit-button {
                background-color: #007bff;
                color: white;
            }

            .submit-button:hover {
                background-color: #0056b3;
            }
        }

        .footer {
            margin-top: 20px;
            font-size: 12px;
            color: #aaa;
        }

        .footer a {
            color: #aaa;
        }

        #token-box {
            display: none;
        }

        #submit-btn {
            display: block;
        }

        .measure-time {
            width: 50%;
            margin: 20px auto;
        }

        .code-content {
            display: flex;
            justify-content: center;
            align-items: center;
            height: 45px;
            font-size: 14px;
        }

        #code {
            margin-left: 10px;
            font-size: 26px;
            letter-spacing: 5px;
            font-weight: 600;
            color: #006fea;
        }

    </style>
</head>
<body>
<div class="login-container">
    <h1>获取 GitHub GHU</h1>
    <div class="form-box">
        <div id="token-box">
            <div class="code-content">
                <div id="code"></div>
            </div>
            <input type="text" id="token" placeholder="正在获取ghu_" readonly/>
            <div id="timeing" class="submit-button measure-time">剩余时间: 900 秒</div>
        </div>
        <div id="submit-btn" class="submit-button" onclick="onSubmit()">登录 GitHub 获取授权码</div>
    </div>

    <div class="footer">
        <a href="https://gitee.com/ripperTs/github-copilot-proxies" target="_blank">Copilot后端代理服务</a>
    </div>
</div>

</body>
<script type="text/javascript">
    let device_code = null;
    let timer = null;

    function countDown(time = 900) {
        const timeing = document.getElementById('timeing');
        timer = setInterval(() => {
            time -= 1;
            timeing.innerText = `剩余时间: ${time} 秒`;
            if (time <= 0) {
                clearInterval(timer);
                document.getElementById('submit-btn').style.display = 'block';
                timeing.style.display = 'none';
                alert("授权码已过期，请重新获取");
                window.location.reload();
            }
        }, 1000);
    }

    async function onSubmit() {
        const response = await fetch('/github/login/device/code', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            }
        })
        if (response.status !== 200) {
            alert('获取授权码失败')
            window.location.reload()
            return
        }
        const resultJson = await response.json()
        confirm(`打开浏览器访问: ${resultJson.verification_uri}, 并输入授权码: ${resultJson.user_code}`)
        copyCode(resultJson.user_code)
        device_code = resultJson.device_code
        document.getElementById('submit-btn').style.display = 'none';
        document.getElementById('token-box').style.display = 'block';
        document.getElementById("code").innerText = resultJson.user_code;
        countDown(resultJson.expires_in);
        window.open(resultJson.verification_uri);
        // 根据user_code获取ghu_token
        await getGhuToken();
    }


    function copyCode(user_code) {
        const input = document.createElement('input');
        input.value = user_code;
        document.body.appendChild(input);
        input.select();
        document.execCommand('copy');
        document.body.removeChild(input);
    }

    async function getGhuToken() {
        await new Promise(resolve => setTimeout(resolve, 5000))
        const response = await fetch('/github/login/ghu-token', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({device_code})
        })
        if (response.status !== 200) {
            alert('获取ghu_token失败')
            window.location.reload()
            return false;
        }
        const resultJson = await response.json()
        if (resultJson.error === "slow_down" && resultJson.error_description === "Too many requests have been made in the same timeframe.") {
            await new Promise(resolve => setTimeout(resolve, resultJson.interval * 1000))
        }

        const access_token = resultJson?.access_token || null
        if (access_token !== null) {
            document.getElementById('token').value = access_token
            clearInterval(timer);
            document.getElementById("timeing").style.display = 'none';
            document.getElementById("code").style.display = 'none';
            return false;
        }
        await getGhuToken()
    }

</script>
</html>
